package cn.jwelll.bxcstock.ui.carin.upload

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.support.v7.widget.LinearLayoutManager
import android.view.KeyEvent
import android.view.View
import cn.jwelll.bxcstock.R
import cn.jwelll.bxcstock.base.DataBindingActivity
import cn.jwelll.bxcstock.bean.TrainUploadRequest
import cn.jwelll.bxcstock.bean.UploadDeleteChildEvent
import cn.jwelll.bxcstock.common.ConstValue
import cn.jwelll.bxcstock.ui.adapter.CommonRecyclerAdapter
import cn.jwelll.bxcstock.ui.dialog.DialogUtils
import cn.jwelll.bxcstock.ui.view.recycleview.HorizontalDividerDecoration
import cn.jwelll.bxcstock.ui.view.recycleview.WrapContentManager
import cn.jwelll.bxcstock.util.*
import cn.jwelll.bxcstock.viewmodel.itemmodel.ItemCarInPreviewModel
import cn.jwelll.bxcstock.viewmodel.itemmodel.ItemCarInUploadModel
import cn.jwelll.bxcstock.viewmodel.itemmodel.UploadDetailModel
import cn.jwelll.bxcstock.viewmodel.viewmodel.CarInPreviewModel
import cn.jwelll.bxcstock.viewmodel.viewmodel.CarInUploadModel
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.android.synthetic.main.activity_carin_preview.*
import kotlinx.android.synthetic.main.layout_title_double.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.text.DecimalFormat


/**
 * 汽运装车 火车装车 的操作界面-确认上传-扫码添加
 */
class CarInUploadActivity :
    DataBindingActivity<CarInUploadModel, CarInUploadContract.View, CarInUploadPresenter>(),
    CarInUploadContract.View {
    companion object {
        const val TYPE_CAR_IN = 100
        const val TYPE_TRAN_IN = 101
    }

    private var mCarInUploadModel = CarInUploadModel()//當前界面的model

    var mShowType = TYPE_CAR_IN// 表示是哪个业务类型
    var mScanCode = ""
    var mRelationId = ""
    var mBillCode = ""
    var mCurrentScanModel: UploadDetailModel? = null//记录当前扫描的model
    var targetList: List<ItemCarInPreviewModel>? = null
    internal var receiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {

            LogUtil.d("receiver-1-${intent.action}")
            LogUtil.d("receiver-2-${intent.getStringExtra("BARCODE")}")
            if (intent.action == "com.barcode.sendBroadcast") {
                LogUtil.d("receiver-1-${intent.getStringExtra("BARCODE")}")
                try {//材料号/品名/规格/牌号/重量
                    //此处兼容两种二维码规格
                    var data = intent.getStringExtra("BARCODE")
                    //过滤空扫描
                    if (data.isEmpty()) {
                        LogUtil.d("data == null")
                        return
                    }
                    //1.第一种规格
                    if (data.split("/").size > 3) {
                        var datas = data.split("/")
                        mCarInUploadModel.materials.forEach {
                            it.childList.forEach {
                                if (datas[0] == it.materialCode) {
                                    showToast("该材料已装车，请勿重复扫码！")
                                    return
                                }
                            }
                        }
                        mCurrentScanModel = UploadDetailModel()
                        mCurrentScanModel!!.materialCode = datas[0]
                        mCurrentScanModel!!.name = datas[1]
                        mCurrentScanModel!!.paiHao = datas[3]

                        mCurrentScanModel!!.weight =
                            DecimalFormat("#.000").format(datas[4].toDouble() / 1000).toDouble()

                        var specification = datas[2]
                        if (datas[2].contains("*")) {
                            specification = datas[2].split("*")[0]
                        }
                        mCurrentScanModel!!.specification = specification
                        showProgress("")
                        mPresenter.validateMaterial(
                            datas[0],
                            datas[1],
                            datas[3],
                            specification,
                            mScanCode,
                            targetList
                        )
                        //2.第二种规格
                    } else {
                        var datas = data.split("\n")
                        mCarInUploadModel.materials.forEach {
                            it.childList.forEach {
                                if (datas[0].split(":")[1] == it.materialCode) {
                                    showToast("该材料已装车，请勿重复扫码！")
                                    return
                                }
                            }
                        }
                        mCurrentScanModel = UploadDetailModel()
                        datas.forEach {
                            if (it.contains("ID:")) {
                                mCurrentScanModel!!.materialCode = it.split(":")[1]
                            } else if (it.contains("品名:")) {
                                mCurrentScanModel!!.name = it.split(":")[1]
                            } else if (it.contains("规格:")) {
                                if (it.contains("*")) {
                                    mCurrentScanModel!!.specification =it.split(":")[1].split("*")[0]
                                } else {
                                    mCurrentScanModel!!.specification = it.split(":")[1]
                                }
                            } else if (it.contains("牌号:")) {
                                mCurrentScanModel!!.paiHao = it.split(":")[1]
                            } else if (it.contains("重量")) {
                                mCurrentScanModel!!.weight =DecimalFormat("#.000").format(it.split(":")[1].split(" ")[0].toDouble() / 1000)
                                        .toDouble()
                            }
                        }

                        mPresenter.validateMaterial(
                            mCurrentScanModel!!.materialCode,
                            mCurrentScanModel!!.name,
                            mCurrentScanModel!!.paiHao,
                            mCurrentScanModel!!.specification,
                            mScanCode,
                            targetList
                        )
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    hideProgress()
                    showToast("二维码不支持扫描，请手动抄写")
                }
            }
        }
    }


    private val mAdapter by lazy {
        CommonRecyclerAdapter<ItemCarInUploadModel>(
            this,
            cn.jwelll.bxcstock.R.layout.item_carin_upload,
            ArrayList()
        ) { v, t, _ ->
        }
    }

    override fun createPresenter() = CarInUploadPresenter(this)

    override fun uploadSuccess() {
        showToast("上传成功")
        finish()
        ActivityUtil.startMainActivityClearTop(this)
    }

    override fun getContentView() = cn.jwelll.bxcstock.R.layout.activity_carin_upload

    override fun getTitleString() = ""
    //界面增加数据，校验是否有过这个品类 没有就增加 有就加入
    override fun validateMaterialSuccess(isRed: Boolean) {
        mCurrentScanModel.let {
            if (mAdapter.data?.size!! > 0) {
                LogUtil.d("validateMaterialSuccess-1-")
                var flag = false
                mAdapter.data?.forEach {
                    it.childList[0]
                    LogUtil.d("validateMaterialSuccess-3-${it.childList[0].name}  ${mCurrentScanModel?.name}")
                    LogUtil.d("validateMaterialSuccess-3-${it.name}  ${mCurrentScanModel?.name}")
                    if (it.name == mCurrentScanModel?.name)//新增小类
                    {
                        flag = true
                        mCurrentScanModel?.isRed = isRed
                        mCurrentScanModel?.index = it.childList.size + 1
                        it.childList.add(mCurrentScanModel!!)
                    }
                }
                LogUtil.d("validateMaterialSuccess-4-$flag")
                if (!flag)//新增大类
                {
                    var itemCarInUploadModel = ItemCarInUploadModel()
                    mCurrentScanModel?.isRed = isRed
                    itemCarInUploadModel.childList.add(mCurrentScanModel!!)
                    itemCarInUploadModel.name = mCurrentScanModel?.name.toString()
                    itemCarInUploadModel.paiHao = mCurrentScanModel?.paiHao.toString()
                    itemCarInUploadModel.specification =
                        mCurrentScanModel?.specification.toString()

                    itemCarInUploadModel.index = mCarInUploadModel.materials?.size + 1
                    mCarInUploadModel.materials?.add(itemCarInUploadModel)
                }
            } else {
                LogUtil.d("validateMaterialSuccess-2-${mCurrentScanModel.toString()}")
                var itemCarInUploadModel = ItemCarInUploadModel()
                itemCarInUploadModel.name = mCurrentScanModel?.name.toString()
                itemCarInUploadModel.paiHao = mCurrentScanModel?.paiHao!!
                itemCarInUploadModel.specification = mCurrentScanModel?.specification!!
                mCurrentScanModel?.isRed = isRed
                itemCarInUploadModel.childList.add(mCurrentScanModel!!)
                mCarInUploadModel.materials?.add(itemCarInUploadModel)
            }
            mAdapter.clear()
            mAdapter.insertData(mCarInUploadModel.materials)

            tv_start_confirm.visibility = View.VISIBLE
            tv_help_info.visibility = View.GONE

            notifyModel(mCarInUploadModel)
            mCurrentScanModel = null
        }
    }

    override fun initData() {
        super.initData()
        mShowType = intent.getIntExtra(ConstValue.INCAR_SHOW_TYPE, TYPE_CAR_IN)

        var mCarInPreviewModel: CarInPreviewModel?
        //转换数据类型
        if (mShowType == TYPE_CAR_IN) {
            var dataString = intent.getStringExtra("model")
            dataString.let {
                mCarInPreviewModel = Gson().fromJson(dataString, CarInPreviewModel::class.java)
            }
            LogUtil.d("initData-$dataString")
            mScanCode = intent.getStringExtra("scancode")
            mCarInPreviewModel.let {
                mCarInUploadModel.id = mCarInPreviewModel?.id!!
                mCarInUploadModel.driverName = mCarInPreviewModel?.driverName!!
                mCarInUploadModel.waybillCode = mCarInPreviewModel?.waybillCode!!
                mCarInUploadModel.qeueuNumber = mCarInPreviewModel?.qeueuNumber!!
                mCarInUploadModel.loadingPoint = mCarInPreviewModel?.loadingPoint!!
            }
        } else {
            mCarInUploadModel.waybillCode = intent.getStringExtra("waybillCode")
            mCarInUploadModel.railwayCode = intent.getStringExtra("railwayCode")
            mCarInUploadModel.remark = intent.getStringExtra("remark")
            mRelationId = intent.getStringExtra("relationId")
            targetList = Gson().fromJson(intent.getStringExtra("targetList"), object :
                TypeToken<List<ItemCarInPreviewModel>>() {

            }.type)
            mBillCode = intent.getStringExtra("billCode")
            LogUtil.d(
                "mRelationId-$mRelationId mBillCode-$mBillCode railwayCode-${intent.getStringExtra(
                    "railwayCode"
                )}"
            )
        }
        notifyModel(mCarInUploadModel)
    }

    override fun initView() {
        super.initView()
        initRecycleView()
        mIbBack.setOnClickListener {
            onQuit()
        }

        if (mShowType == TYPE_CAR_IN) {
            ll_top_carin.visibility = View.VISIBLE
            ll_top_trainin.visibility = View.GONE
            titleString = "${SPUtils.getString(this, ConstValue.WARE_HOUSE_NAME, "")}汽车装车出库"

        } else {
            titleString = "${SPUtils.getString(this, ConstValue.WARE_HOUSE_NAME, "")}火车装车出库"
            ll_top_carin.visibility = View.GONE
            ll_top_trainin.visibility = View.VISIBLE
        }
    }

    override fun onResume() {
        super.onResume()
        ScanHelper.setScanSwitchLeft(this, true);
        ScanHelper.setScanSwitchRight(this, true);
        ScanHelper.setBarcodeReceiveModel(this, 2);

        var intentFilter = IntentFilter();
        intentFilter.addAction("com.barcode.sendBroadcast");
        registerReceiver(receiver, intentFilter)

    }

    override fun onPause() {
        super.onPause()
        unregisterReceiver(receiver)
    }

    //刪除子項的處理
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(event: UploadDeleteChildEvent) {
        mCarInUploadModel.weight -= mCarInUploadModel.materials[event.index - 1].childList[event.childIndex].weight

        mCarInUploadModel.materials[event.index - 1].childList.removeAt(event.childIndex)
        if (mCarInUploadModel.materials[event.index - 1].childList.size <= 0)//當前沒有小item 就移除當前大item
        {
            mCarInUploadModel.materials.removeAt(event.index - 1)

            for ((index, value) in mCarInUploadModel.materials.withIndex()) {
                value.index = index + 1
            }

        } else //就重新更新小item序號
        {
            for ((index, value) in mCarInUploadModel.materials[event.index - 1].childList.withIndex()) {
                value.index = index + 1
            }
        }

        mAdapter.clear()

        tv_start_confirm.visibility =
            if (mCarInUploadModel.materials.size > 0) View.VISIBLE else View.GONE
        tv_help_info.visibility =
            if (mCarInUploadModel.materials.size == 0) View.VISIBLE else View.GONE
        mAdapter.insertData(mCarInUploadModel.materials)

        notifyModel(mCarInUploadModel)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    override fun initEvent() {
        super.initEvent()
        EventBus.getDefault().register(this)
        tv_start_confirm.setOnClickListener {
            if (mAdapter.data?.size == 0) {
                showToast("请开始扫描采集！")
                return@setOnClickListener
            }

            DialogUtils.Builder(this).setMessage("确定完成采集，进行上传？").setPositiveButton(
                "确定", R.color.color_2f5aff
            ) {
                var list = ArrayList<UploadDetailModel>()
                mCarInUploadModel?.materials?.forEach {
                    list.addAll(it.childList)
                }
                showProgress("上传中，请稍后")
                if (mShowType == TYPE_CAR_IN) {
                    if (mCarInUploadModel != null) {
                        mPresenter.carUpload(
                            mScanCode,
                            mCarInUploadModel?.waybillCode!!,
                            mCarInUploadModel?.driverName!!,
                            mCarInUploadModel?.carNum!!,
                            mCarInUploadModel?.qeueuNumber!!,
                            mCarInUploadModel?.loadingPoint!!,
                            mCarInUploadModel?.weight!!, list
                        )
                    } else {
                        showToast("数据错误，请退出当前界面重试！")
                    }
                } else {
                    var request = TrainUploadRequest()
                    request.materials = list
                    request.railwayCode = mCarInUploadModel.railwayCode
                    request.billCode = mBillCode
                    request.relationId = mRelationId

                    mPresenter.trainUpload(request)
                }
            }.setNegativeButton("取消", R.color.color_999999) {
            }.creat().show()
        }
    }

    private fun initRecycleView() {
        val mLinearLayoutManager = WrapContentManager(this, LinearLayoutManager.VERTICAL, false)
        recycler_view.layoutManager = mLinearLayoutManager
        recycler_view.addItemDecoration(
            HorizontalDividerDecoration(
                this,
                cn.jwelll.bxcstock.R.drawable.divider_horizontal_10_ffffff,
                DisplayUtil.dip2px(this, 10f)
            )
        )
        recycler_view.setHasFixedSize(true)
        recycler_view.setLoadingMoreEnabled(false)
        recycler_view.setPullRefreshEnabled(false)
        recycler_view.refreshComplete()
        recycler_view.loadMoreComplete()

        recycler_view.adapter = mAdapter
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onQuit()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onOverrideBackClick(): Boolean {
        return true
    }

    fun onQuit() {
        DialogUtils.Builder(this).setMessage("确定退出采集操作？").setPositiveButton(
            "确定", cn.jwelll.bxcstock.R.color.color_2f5aff
        ) {
            finish()
        }.setNegativeButton("取消", cn.jwelll.bxcstock.R.color.color_999999) {}.creat().show()
    }
}